package com.cl.edu.web.admin;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.cl.common.util.UploadUtils;
import com.opensymphony.xwork2.ActionSupport;

public class GuanggaoAction extends ActionSupport{
	
	private File guanggao; // 上传的文件
	private String guanggaoFileName; // 上传的文件名称
	private String guanggaoContentType; // 上传的文件类型
	
	private String savePath = File.separator+"upload"+File.separator+"guanggao";
	
	public String left() throws Exception{
		init("left.jpg");
		return SUCCESS;
	}
	
	public String middle() throws Exception{
		init("middle.jpg");
		return SUCCESS;
	}

	public String bottom() throws Exception{
		init("bottom.jpg");
		return SUCCESS;
	}
	
	public void init(String filename) {
		// 获取扩展名
		String ext = UploadUtils.getExtension(guanggaoFileName);
		if (!"jpg".equals(ext)) {
			addActionMessage("照片扩展名不符合要求!");
			return;
		}
		long size = guanggao.length();
		if (size > 1024 * 1024 * 512) {
			addActionMessage("照片大小不能大于512K!");
			return;
		}
		String fullPath = getSavePath() + File.separator+filename;
		String parentFolder = UploadUtils.getParentFolder(fullPath);
		try {
			//存入物理文件
			File file = new File(parentFolder);
			UploadUtils.checkDirAndCreate(file);
			FileOutputStream fos = new FileOutputStream(fullPath);
			FileInputStream fis = new FileInputStream(getGuanggao());
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			
			addActionMessage("上传成功!");
			
		} catch (Exception e) {
			addActionMessage("上传失败!");
			e.printStackTrace();
		}
	}

	public File getGuanggao() {
		return guanggao;
	}

	public void setGuanggao(File guanggao) {
		this.guanggao = guanggao;
	}

	public String getGuanggaoFileName() {
		return guanggaoFileName;
	}

	public void setGuanggaoFileName(String guanggaoFileName) {
		this.guanggaoFileName = guanggaoFileName;
	}

	public String getGuanggaoContentType() {
		return guanggaoContentType;
	}

	public void setGuanggaoContentType(String guanggaoContentType) {
		this.guanggaoContentType = guanggaoContentType;
	}
	
	public String getSavePath() {
		return ServletActionContext.getRequest().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	
}
